<?php
/*
 * 前端令牌控制器
 */
class TokenController extends BasicController {
    
    private function init(){
        Yaf_Registry::get('tokenPlugin')->checkAuth();
    }

    /*
    * 默认控制器 
    */
    public function indexAction(){
        echo '你好：'.G_USER_ID;
    }
    
    /*
    * 校验token是否有效 
    */
    public function checktokenAction(){
        // 1.接收传递过来的token
        $params = $this->getPost();
        
        $cToken = isset($params['ctoken']) ? $params['ctoken'] : '';//需要校验的 token
        
        if(!$cToken){//如果传递内容为空的话
            $return['code'] = "1";
            $return['msg'] = '参数错误！';
            
            echo json_encode($return);
            return false;
        }
        
        $tokenModel = Helper::load('Token');
        
        $r = $tokenModel->checkToken($cToken);
        
        if($r){
            $return['code'] = "0";
            $return['msg'] = '令牌有效！';
        }
        else{
            $return['code'] = "2";
            $return['msg'] = '令牌失效！';
        }
        
        echo json_encode($return);
        return false;
    }
    
    /*
    * 观察者角色生成新token 
    * ed54ESaYnnNBRbspi1uZNJSOHoEyRs/SJcvL6VFxUZXl6W7ANjTW2CFmyTw
    */
    public function observerAction(){
        // 1.接收传递过来的用户名和秘钥
        $params = $this->getPost();
        
        $uname = isset($params['uname']) ? $params['uname'] : '';//用户名
        $usecret = isset($params['usecret']) ? $params['usecret'] : '';//秘钥
        
        if(!$uname || !$usecret){//如果传递内容为空的话
            $return['code'] = "1";
            $return['msg'] = '参数错误！';
            
            echo json_encode($return);
            return false;
        }
        
        // 2.判断一下传递过来的用户名与秘钥是否有效，有效的话拉取对应的uid
        $thirdModel = Helper::load('Third');
        $thirdArr = $thirdModel::$thirdArr;
        
        if(!isset($thirdArr[$uname])){//不存在对应的第三方
            $return['code'] = "2";
            $return['msg'] = '无效用户！';
            
            echo json_encode($return);
            return false;
        }
        
        if(strtolower($usecret) != $thirdArr[$uname]['usecret']){//秘钥错误
            $return['code'] = "2";
            $return['msg'] = '无效用户！';
            
            echo json_encode($return);
            return false;
        }
        
        $return['code'] = "0";
        $return['msg'] = '操作成功！';
        
        $user_id = $thirdArr[$uname]['uid'];
        $randTime = CUR_TIMESTAMP;
        $token = authcode("0\t$user_id\t$randTime", 'ENCODE');
        
        $return['data']['token'] = $token;
        
        $tokenModel = Helper::load('Token');
        
        $tokenModel->insertToken($token, $user_id);
        
        echo json_encode($return);
        return false;
    }
    
}